package com.cndw.kungfu.socket;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * 解码
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-5-18
 */
public class ClientFrameDecoder extends FrameDecoder {

	private int bodySize;
	private int frameStatus;
	private static final int FRAME_READ_HEAD = 0;
	private static final int FRAME_READ_BODY = 1;

	@Override
	protected Object decode(ChannelHandlerContext channelhandlercontext, Channel channel, ChannelBuffer channelbuffer) throws Exception {

		switch (frameStatus) {

		case FRAME_READ_HEAD:

			if (channelbuffer.readableBytes() >= 4) {
				frameStatus = FRAME_READ_BODY;
				bodySize = channelbuffer.readInt();
			}

		case FRAME_READ_BODY:

			if (channelbuffer.readableBytes() >= bodySize) {
				frameStatus = FRAME_READ_HEAD;
				ChannelBuffer buffer = channelbuffer.factory().getBuffer(bodySize);
				buffer.writeBytes(channelbuffer, bodySize);
				return buffer;
			}

		default:
			return null;
		}
	}
}
